import wxappUser from '@caomei/wxapp-user';
import { setGlobalBeforeRequestHandler } from 'wxapp-request';
import { assign } from 'lodash';
import { autoOpenSettingWhenNeedAuth } from './utils/openSetting';
import env from './env';
import { createUrl } from './utils/util';

// 给每一个请求带上token
setGlobalBeforeRequestHandler((options) => {
  if (!options.withoutToken) {
    if (!wxappUser.token) {
      return Promise.reject(new Error('小程序还未登录'));
    }
    return assign({}, options, {
      url: createUrl(options.url, `token=${wxappUser.token}`),
    });
  }
  return options;
});
function login() {
  console.log('登录中');
  return autoOpenSettingWhenNeedAuth(() => wxappUser.login({
    serverOptions: {
      apiUrl: env.API_URL,
      appId: env.APP_ID,
    },
  }));
}

App({
  onLaunch() {
    // 第一次登录
    login()
      .catch((err) => {
        console.error(err);
      });
  },
  onError(err) {
    console.error(err);
  },
});
